package cn.myzf.module.container;

import cn.myzf.module.handler.HttpRequestHandler;
import cn.myzf.module.routes.HttpServlet;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;


public class WebConfigContainer implements Container {


    private NioEventLoopGroup serverWorkerGroup;

    private NioEventLoopGroup serverBossGroup;

    private HttpServlet httpServlet;



    public WebConfigContainer() {


        // 配置管理，并发处理很小，使用单线程处理网络事件
        serverBossGroup = new NioEventLoopGroup(1);
        serverWorkerGroup = new NioEventLoopGroup(1);

    }


    public void setHttpServlet(HttpServlet httpServlet) {
        this.httpServlet = httpServlet;
    }

    @Override
    public void start() {
        ServerBootstrap httpServerBootstrap = new ServerBootstrap();
        httpServerBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024*1024*64));
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new HttpRequestHandler(httpServlet));
                    }
                });

        try {
            httpServerBootstrap.bind("0.0.0.0",9000).get();
          //  logger.info("http server start on port " + ProxyConfig.getInstance().getConfigServerPort());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }


    }

    @Override
    public void stop() {
        serverBossGroup.shutdownGracefully();
        serverWorkerGroup.shutdownGracefully();
    }

}
